<template>
  <div class="collection-page">
    <el-row :gutter="20">
      <el-col v-for="(item, index) in collectionList" :key="index" :span="6">
        <el-card shadow="hover" class="collection-item">
          <el-image
              :src="'/api/file/images/' + item.goods.picList[0].url"
              fit="contain"
              style="width: 100%; height: 200px; object-fit: cover;"
          />
          <div class="info">
            <div class="name">{{ item.goods.name }}</div>
            <div class="price">售价: ￥{{ item.goods.price }}</div>
            <div class="dscp">{{ item.goods.dscp }}</div>
          </div>
          <div class="actions">
            <el-button type="primary" size="mini" @click="viewItem(item.id)">查看详情</el-button>
            <el-button type="danger" size="mini" @click="removeCollect(item.id)">移除收藏</el-button>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import collectApi from '@/api/collect.js';
import { ElMessage } from 'element-plus';
import { useRouter } from 'vue-router';

const collectionList = ref([]);
const router = useRouter();

// 获取用户的收藏列表
const getCollectionList = async () => {
  try {
    const response = await collectApi.getList();
    if (response.code === 10000) {
      collectionList.value = response.data;
    } else {
      ElMessage.error('获取收藏列表失败');
    }
  } catch (error) {
    ElMessage.error('网络错误');
  }
};

// 查看商品详情
const viewItem = (id) => {
  router.push({ path: '/user/goods', query: { id } });
};

// 移除收藏
const removeCollect = async (id) => {
  try {
    const response = await collectApi.del(id);
    if (response.code === 10000) {
      ElMessage.success('移除收藏成功');
      getCollectionList(); // 更新收藏列表
    } else {
      ElMessage.error(response.msg || '移除收藏失败');
    }
  } catch (error) {
    ElMessage.error('网络错误');
  }
};

// 初始化获取收藏列表
onMounted(() => {
  getCollectionList();
});
</script>

<style scoped>
.collection-page {
  padding: 20px;
}

.collection-item {
  text-align: center;
}

.info {
  margin-top: 10px;
  font-size: 14px;
}

.name {
  font-weight: bold;
  font-size: 16px;
  margin-bottom: 5px;
}

.price {
  color: var(--theme-color);
  font-size: 16px;
  margin-bottom: 10px;
}

.dscp {
  color: #999999;
  font-size: 13px;
  margin-bottom: 10px;
}

.actions {
  display: flex;
  justify-content: space-between;
  margin-top: 10px;
}
</style>
